package com.hui.jwt.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hui.jwt.config.JwtProperties;
import com.hui.jwt.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * @BelongsProject: SpringSecurity-jwt
 * @BelongsPackage: com.hui.jwt.security
 * @Author: HUI
 * @CreateTime: 2022-04-02 20:51
 * @Description:
 */


/**
 * 自定义认证成功处理器
 */
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        System.err.println(jwtProperties.getBase64Secret());
        System.err.println(jwtProperties.getHeader());
        System.err.println(jwtProperties.getTokenValidityInSeconds());
        //生成token
        final String realToken = jwtTokenUtil.generateToken(authentication.getName());
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", realToken);
        map.put("message", "登录成功");


        //将生成的authentication放入容器中，生成安全的上下文
        SecurityContextHolder.getContext().setAuthentication(authentication);

        response.setStatus(HttpStatus.OK.value());
        response.setContentType("text/json;charset=utf-8");

        String s = new ObjectMapper().writeValueAsString(map);

        response.getWriter().println(s);


    }
}
